<template>
  <div>
    <div v-show="visible" v-permission="['base-data:product:info:sales:query']">
      <a-row>
        <a-col :span="4">
          <page-wrapper content-full-height fixed-height content-class="!mr-0">
            <category-tree
              style="height: 100%"
              :category-types="searchFormData.categoryTypes"
              @change="treeNodeChange"
            />
          </page-wrapper>
        </a-col>
        <a-col :span="20">
          <page-wrapper content-full-height fixed-height>
            <!-- 数据列表 -->
            <vxe-grid
              id="salesProductInfoGrid"
              ref="grid"
              resizable
              show-overflow
              highlight-hover-row
              keep-source
              row-id="id"
              :proxy-config="proxyConfig"
              :columns="tableColumn"
              :toolbar-config="toolbarConfig"
              :custom-config="{}"
              :pager-config="{}"
              :row-config="{
                height: 60,
              }"
              :loading="loading"
              height="auto"
            >
              <template #form>
                <j-border>
                  <j-form bordered @collapse="$refs.grid.refreshColumn()">
                    <j-form-item label="所属门店">
                      <span v-if="$utils.isEmpty(shopId)">总部</span>
                      <shop-selector v-else :value="shopId" readOnly />
                    </j-form-item>
                    <j-form-item label="编号">
                      <a-input v-model:value="searchFormData.code" allow-clear />
                    </j-form-item>
                    <j-form-item label="名称">
                      <a-input v-model:value="searchFormData.name" allow-clear />
                    </j-form-item>
                    <j-form-item label="简称">
                      <a-input v-model:value="searchFormData.shortName" allow-clear />
                    </j-form-item>
                    <j-form-item label="SKU编号">
                      <a-input v-model:value="searchFormData.skuCode" allow-clear />
                    </j-form-item>
                    <j-form-item label="品牌">
                      <product-brand-selector v-model:value="searchFormData.brandId" />
                    </j-form-item>
                    <j-form-item label="商品类型">
                      <a-select
                        v-model:value="searchFormData.productType"
                        placeholder="全部"
                        allow-clear
                      >
                        <a-select-option
                          v-for="item in $enums.PRODUCT_TYPE.values()"
                          :key="item.code"
                          :value="item.code"
                          >{{ item.desc }}</a-select-option
                        >
                      </a-select>
                    </j-form-item>
                    <j-form-item label="创建日期" :content-nest="false">
                      <div class="date-range-container">
                        <a-date-picker
                          v-model:value="searchFormData.startTime"
                          placeholder=""
                          value-format="YYYY-MM-DD 00:00:00"
                        />
                        <span class="date-split">至</span>
                        <a-date-picker
                          v-model:value="searchFormData.endTime"
                          placeholder=""
                          value-format="YYYY-MM-DD 23:59:59"
                        />
                      </div>
                    </j-form-item>
                    <j-form-item label="状态">
                      <a-select
                        v-model:value="searchFormData.available"
                        placeholder="全部"
                        allow-clear
                      >
                        <a-select-option
                          v-for="item in $enums.AVAILABLE.values()"
                          :key="item.code"
                          :value="item.code"
                          >{{ item.desc }}</a-select-option
                        >
                      </a-select>
                    </j-form-item>
                  </j-form>
                </j-border>
              </template>
              <!-- 工具栏 -->
              <template #toolbar_buttons>
                <a-space>
                  <a-button type="primary" :icon="h(SearchOutlined)" @click="search">查询</a-button>
                  <a-button
                    v-if="!selectorMode"
                    v-permission="['base-data:product:info:sales:add']"
                    type="primary"
                    :icon="h(PlusOutlined)"
                    @click="openAddDialog"
                  >
                    新增
                  </a-button>
                  <a-button
                    class="c-button-warning"
                    v-if="!selectorMode"
                    v-permission="['base-data:product:info:sales:sync']"
                    :icon="h(CloudSyncOutlined)"
                    type="ghost"
                    @click="openSyncDialog"
                  >
                    同步至多门店
                  </a-button>
                  <a-button
                    v-if="!selectorMode"
                    v-permission="['base-data:product:info:sales:import']"
                    :icon="h(CloudUploadOutlined)"
                    @click="$refs.importer.openDialog()"
                  >
                    导入Excel
                  </a-button>
                </a-space>
              </template>

              <!-- 状态 列自定义内容 -->
              <template #available_default="{ row }">
                <available-tag :available="row.available" />
              </template>

              <!-- 商品图片 列自定义内容 -->
              <template #imageUrl_default="{ row }">
                <div v-if="row.imageUrl" class="product-image-container">
                  <a-image
                    :src="row.imageUrl"
                    :alt="row.name"
                    class="product-image"
                    @click="previewImage(row.imageUrl, row.name)"
                  />
                </div>
                <span v-else class="no-image">无图片</span>
              </template>

              <!-- 操作 列自定义内容 -->
              <template #action_default="{ row }">
                <table-action
                  outside
                  :actions="createActions(row)"
                  :drop-down-actions="createDropDownActions(row)"
                />
              </template>
            </vxe-grid>
          </page-wrapper>
        </a-col>
      </a-row>

      <!-- 新增窗口 -->
      <add
        :category-types="searchFormData.categoryTypes"
        :shop-id="searchFormData.shopId"
        ref="addDialog"
        @confirm="search"
      />

      <!-- 修改窗口 -->
      <modify
        :id="id"
        :category-types="searchFormData.categoryTypes"
        ref="modifyDialog"
        @confirm="search"
      />

      <!-- 查看窗口 -->
      <detail :id="id" ref="viewDialog" />

      <!-- 同步窗口 -->
      <sync-dialog :sync-type="'sales'" :shop-id="shopId" ref="syncDialogRef" />

      <!-- 辅料窗口 -->
      <assistance-edit ref="assistanceEdit" :product-id="currentProductId" />

      <!-- 多单位 -->
      <unit-edit ref="unitEdit" :product-id="currentProductId" />
    </div>

    <product-importer ref="importer" @confirm="search" />
  </div>
</template>

<script>
  import { h, defineComponent, defineAsyncComponent } from 'vue';
  import Add from './add.vue';
  import Modify from './modify.vue';
  import Detail from './detail.vue';
  import * as api from '@/api/base-data/product/info';
  import {
    CloudSyncOutlined,
    CloudUploadOutlined,
    PlusOutlined,
    SearchOutlined,
  } from '@ant-design/icons-vue';
  import { multiplePageMix } from '@/mixins/multiplePageMix';
  import AssistanceEdit from '@/views/base-data/product/assistanceEdit.vue';
  import CategoryTree from '@/views/base-data/product/category/category-tree.vue';
  import ShopSelector from '@/components/Selector/src/ShopSelector.vue';
  import UnitEdit from '@/views/base-data/product/unitEdit.vue';

  export default defineComponent({
    name: 'SalesProductInfo',
    components: {
      UnitEdit,
      ShopSelector,
      SyncDialog: defineAsyncComponent(() => import('@/views/base-data/product/sync/index.vue')),
      Modify,
      Add,
      CategoryTree,
      AssistanceEdit,
      Detail,
    },
    mixins: [multiplePageMix],
    props: {
      selectorMode: {
        type: Boolean,
        default: false,
      },
      shopId: {
        type: String,
        default: '',
      },
    },
    setup() {
      return {
        h,
        CloudUploadOutlined,
        PlusOutlined,
        SearchOutlined,
        CloudSyncOutlined,
      };
    },
    data() {
      return {
        loading: false,
        visible: true,
        // 当前行数据
        id: '',
        ids: [],
        // 成本卡相关数据
        costCardVisible: false,
        currentProductId: '',
        // 查询列表的查询条件
        searchFormData: {
          code: '',
          name: '',
          skuCode: '',
          categoryId: '',
          categoryTypes: '2',
          brandId: '',
          startTime: '',
          endTime: '',
          available: this.$enums.AVAILABLE.ENABLE.code,
        },
        // 工具栏配置
        toolbarConfig: {
          // 自定义左侧工具栏
          slots: {
            buttons: 'toolbar_buttons',
          },
        },
        // 列表数据配置
        tableColumn: [
          { type: 'checkbox', width: 45 },
          { field: 'code', title: '编号', width: 120, sortable: true },
          { field: 'name', title: '名称', minWidth: 120, sortable: true },
          { field: 'shortName', title: '简称', minWidth: 60 },
          { field: 'skuCode', title: 'SKU编号', width: 120 },
          { field: 'categoryName', title: '分类', width: 120 },
          { field: 'brandName', title: '品牌', minWidth: 140 },
          {
            field: 'imageUrl',
            title: '商品图片',
            width: 100,
            slots: { default: 'imageUrl_default' },
          },
          {
            field: 'productType',
            title: '商品类型',
            width: 120,
            formatter: ({ cellValue }) => {
              return this.$enums.PRODUCT_TYPE.getDesc(cellValue);
            },
          },
          { field: 'available', title: '状态', width: 80, slots: { default: 'available_default' } },
          { field: 'createTime', title: '创建时间', width: 170, sortable: true },
          { field: 'updateTime', title: '修改时间', width: 170, sortable: true },
          {
            title: '操作',
            width: 190,
            fixed: 'right',
            visible: !this.selectorMode,
            slots: { default: 'action_default' },
          },
        ],
        // 请求接口配置
        proxyConfig: {
          props: {
            // 响应结果列表字段
            result: 'datas',
            // 响应结果总条数字段
            total: 'totalCount',
          },
          ajax: {
            // 查询接口
            query: ({ page, sorts }) => {
              return api.query(this.buildQueryParams(page, sorts));
            },
          },
        },
      };
    },
    created() {},
    methods: {
      // 列表发生查询时的事件
      search() {
        this.$refs.grid.commitProxy('reload');
      },
      // 查询前构建查询参数结构
      buildQueryParams(page, sorts) {
        return {
          ...this.$utils.buildSortPageVo(page, sorts),
          ...this.buildSearchFormData(),
        };
      },
      // 查询前构建具体的查询参数
      buildSearchFormData() {
        return {
          ...this.searchFormData,
          shopIds: this.shopId,
        };
      },
      createActions(row) {
        return [
          {
            permission: ['base-data:product:info:sales:query'],
            label: '查看',
            onClick: () => {
              this.id = row.id;
              this.$nextTick(() => this.$refs.viewDialog.openDialog());
            },
          },
          {
            permission: ['base-data:product:info:sales:modify'],
            label: '修改',
            onClick: () => {
              this.id = row.id;
              this.$nextTick(() => this.$refs.modifyDialog.openDialog());
            },
          },
          {
            permission: ['base-data:product:info:sales:add'],
            label: '复制',
            onClick: () => {
              this.$nextTick(() => this.$refs.addDialog.openDialog(row.id));
            },
          },
        ];
      },
      createDropDownActions(row) {
        const dropDownActions = [];
        if ([1, 3].includes(row.productType)) {
          dropDownActions.push({
            permission: ['base-data:product:assistance:unit:query'],
            label: '多单位',
            onClick: () => {
              this.currentProductId = row.id;
              this.openUnitEditDialog(row);
            },
          });
          dropDownActions.push({
            permission: ['base-data:product:costcard:query'],
            label: '辅料',
            onClick: () => {
              this.openAssistanceEditDialog(row);
            },
          });
        }
        return dropDownActions;
      },
      // 打开新增对话框
      openAddDialog() {
        this.$nextTick(() => this.$refs.addDialog.openDialog());
      },
      // 打开同步对话框
      openSyncDialog() {
        this.$nextTick(() => this.$refs.syncDialogRef.openDialog());
      },
      // 打开辅料管理对话框
      openAssistanceEditDialog(row) {
        this.currentProductId = row.id;
        this.$refs.assistanceEdit.openDialog(row);
      },
      // 打开规格管理对话框
      openSpecEditDialog(row) {
        this.$refs.specEdit.openDialog(row.id);
      },
      // 打开成本卡管理对话框
      openCostCardDialog(row) {
        this.costCardVisible = true;
        this.currentProductId = row.id;
      },
      // 预览图片
      previewImage(imageUrl, title) {
        this.$preview.preview({
          current: imageUrl,
          urls: [imageUrl],
          title: title || '商品图片',
        });
      },
      onRefreshPage() {
        this.search();
      },
      treeNodeChange(node) {
        if (node === 0) {
          this.searchFormData.categoryId = null;
        } else {
          this.searchFormData.categoryId = node;
        }
        this.search();
      },
      // 获取选择器数据
      getSelectedRows() {
        return this.$refs.grid.getCheckboxRecords();
      },
    },
  });
</script>
<style scoped>
  .product-image-container {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .product-image {
    width: 50px;
    height: 30px;
    object-fit: cover;
    border-radius: 4px;
    cursor: pointer;
    border: 1px solid #d9d9d9;
    transition: all 0.3s;
  }

  .product-image:hover {
    transform: scale(1.1);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  .no-image {
    color: #999;
    font-size: 12px;
  }
</style>
